<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head th:include="_header_include::frag(~{::title},~{},~{})">
    <title>字典词条</title>
</head>
<body>

<div id="queryForm" class="mainPadding" style="display: none;padding-bottom: 0;">

    <el-breadcrumb separator="/" class="elBreadcrumb marginB20">
        <el-breadcrumb-item>Home</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>词条管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-row class="row-bg" justify="start">
        <el-col :span="18">
            <el-button type="primary" @click="openAddDialog()"><i class="el-icon-plus"></i>添加词条</el-button>
            <el-button type="success" @click="openUpdateDialog()"><i class="el-icon-edit"></i>编辑词条</el-button>
            <el-button type="danger" @click="deleteDic()"><i class="el-icon-delete"></i>删除词条</el-button>
        </el-col>
        <el-col :span="6" style="text-align: right;">
            <el-form :model="formInline" ref="queryForm"  @submit.native.prevent>
                <el-form-item label="" prop="name" style="margin: 0;">
                    <el-input v-model="formInline.name" placeholder="请输入名称进行查询">
                        <el-button slot="append" icon="el-icon-search" @click="onSubmit">搜索</el-button>
                    </el-input>
                    <el-input type="hidden" v-model="formInline.groupCode" style="width: 0;float: right;"></el-input>
                    <el-input type="hidden" v-model="formInline.dicId" style="width: 0;float: right;"></el-input>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</div>

<div id="pagination" class="mainPadding">
    <div class="mainSearchBg">
        <template>
            <el-table :data="tableData3" border style="width: 100%" tooltip-effect="dark"  ref="multipleTable"  @select="selectRow"
                      @selection-change="handleSelectionChange" >
                <el-table-column type="selection" width="55" prop="id"> </el-table-column>
                <el-table-column prop="name" label="名称" width="180" align="center"></el-table-column>
                <el-table-column prop="value" label="编码" width="180" align="center"></el-table-column>
                <el-table-column prop="sortNo" label="排序序号" align="center"></el-table-column>
            </el-table>
        </template>

        <template>
            <div class="block">
                <el-pagination @size-change="handleSizeChange"
                               @current-change="handleCurrentChange" :current-page="currentPage"
                               :page-sizes="[20, 50, 100]" :page-size="pageSize"
                               layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </template>
    </div>
</div>

<!--添加弹窗-->
<div id="addDialog">
    <template>
        <el-dialog title="添加词条"  :visible.sync="dialogFormVisible"  width="540px">
            <el-form :model="add" ref="add" :rules="rules">
                <el-form-item label="名称："  :label-width="formLabelWidth"  prop="name">
                    <el-input v-model="add.name" autocomplete="off"  maxlength="100" style="width: 290px"></el-input>
                </el-form-item>
                <el-form-item label="编码："  :label-width="formLabelWidth"  prop="value">
                    <el-input v-model="add.value" autocomplete="off"  maxlength="100" style="width: 290px"></el-input>
                </el-form-item>
                <el-form-item label="排序序号：" :label-width="formLabelWidth"   prop="sortNo">
                    <el-input type="number" v-model="add.sortNo" autocomplete="off" maxlength="50" style="width: 290px"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="saveOneDictionaryItem">确 定</el-button>
                <el-button @click="dialogFormVisible = false">取 消</el-button>
            </div>
        </el-dialog>
    </template>
</div>


<div id="updateDialog">
    <template>
        <el-dialog title="编辑词条"  :visible.sync="updateDialogFormVisible"  width="540px">
            <el-form :model="add" ref="add" :rules="rules">
                <el-form-item label="名称："  :label-width="formLabelWidth" prop="name">
                    <el-input v-model="add.name" autocomplete="off"  maxlength="100" style="width: 290px"></el-input>
                </el-form-item>
                <el-form-item label="编码："  :label-width="formLabelWidth"  prop="value">
                    <el-input v-model="add.value" autocomplete="off" maxlength="200" style="width: 290px"></el-input>
                </el-form-item>
                <el-form-item label="排序序号："  :label-width="formLabelWidth"  prop="sortNo">
                    <el-input type="number" v-model="add.sortNo"  maxlength="50" autocomplete="off" style="width: 290px"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="update">确 定</el-button>
                <el-button @click="updateDialogFormVisible = false">取 消</el-button>
            </div>
        </el-dialog>

    </template>
</div>
<!-- import common js-->
<div th:include="_footer_include :: #jsLib"></div>

<script>
    // <!--删除提示弹窗 -->
    const validateAcquaintance = (rule, value, callback) => {
        if (!value) {
            callback(new Error('必须输入'))
        }
        value = Number(value)
        if (value!='e' && typeof value === 'number' && !isNaN(value)) {
            if (value < 0 || value > 999) {
                callback(new Error('输入的值在 0 至 999之间'))
            } else {
                callback()
            }
        } else {
            callback(new Error('必须为数字'))
        }
    }

    var updateDialogVm = new Vue({
        el: '#updateDialog',
        data:{
            formLabelWidth:"120px",
            updateDialogFormVisible:false,
            add:{
                name:"",
                value:"",
                sortNo:""
            },
            rules: {
                name: [
                    {required: true, message: '请输入词条名称', trigger: 'blur'},
                    {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
                ],
                value: [
                    {required: true, message: '请输入词条编码', trigger: 'blur'},
                    {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
                ],
                sortNo:[
                    {required: true, message: '请输入排序序号', trigger: 'blur'},
                    {
                        validator: validateAcquaintance, // 自定义验证
                        trigger: 'blur'
                    }
                ]
            }
        },
        methods:{
            initUpdateData(v_id){
                var param = {};
                param.id = v_id;
                axios.post('/dictionary/DictionaryItem/findByPrimaryKey', param)
                    .then(function (response) {
                        console.log(response.data.data)
                        updateDialogVm.add = response.data.data;
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },  update(){
                var param =  updateDialogVm.add;
                param.id =  paginationVm.multipleSelection[0].id;
                param.dicId = paginationVm.dicid;
                this.$refs['add'].validate((valid) => {
                    if (valid) {
                        axios.post('/dictionary/DictionaryItem/updateDictionaryItem', param)
                            .then(function (response) {
                                console.log(response.data)
                                if (response.data.code == 0) {
                                    updateDialogVm.$message({
                                        type: 'success', message: '更新成功!', duration: 2000, onClose: function () {
                                            paginationVm.initTableData(paginationVm.pageNum);
                                            updateDialogVm.updateDialogFormVisible = false;
                                        }
                                    });
                                } else {
                                    updateDialogVm.$message.error(response.data.msg);
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                            });
                    } else {
                        console.log('数据未通过校验！');
                        return false;
                    }
                })
            },
            showOutVisiable:function(){
                this.updateDialogFormVisible = true
            },
            resetForm(formName) {
                if(updateDialogVm.$refs[formName])
                    updateDialogVm.$refs[formName].resetFields();
            },
        },
        created() {
            console.info("create method");
            // this.initUpdateData(1);
        },

    });
    // <!--新增弹窗 -->
    var addDialogVm = new Vue({
        el: '#addDialog',
        data:{
            formLabelWidth:"120px",
            dialogFormVisible:false,
            add:{
                name:"",
                value:"",
                sortNo:""
            },
            rules: {
                name: [
                    {required: true, message: '请输入词条名称', trigger: 'blur'},
                    {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
                ],
                value: [
                    {required: true, message: '请输入词条编码', trigger: 'blur'},
                    {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
                ],
                sortNo:[
                    {required: true, message: '请输入排序序号', trigger: 'blur'},
                    {
                        validator: validateAcquaintance, // 自定义验证
                        trigger: 'blur'
                    }
                ]
            }
        },
        methods:{
            showOutVisiable:function(){
                this.dialogFormVisible = true
            },
            saveOneDictionaryItem:function(){
                var param = addDialogVm.add;
                param.dicId = paginationVm.dicid;
                param.groupCode = paginationVm.groupCode;
                console.log("---------------------------------")
                console.log(param)
                this.$refs['add'].validate((valid) => {
                    if (valid) {
                        axios.post('/dictionary/DictionaryItem/saveDictionaryItem', param)
                            .then(function (response) {
                                if(response.data.code==0){
                                    addDialogVm.$message({type: 'success', message: '插入成功!',duration:2000,onClose:function(){
                                            paginationVm.initTableData(1);
                                        }});
                                    addDialogVm.dialogFormVisible = false;

                                }else{
                                    console.log(response.data)
                                    addDialogVm.$message.error(response.data.msg);
                                }
                            })
                            .catch(function (error) {
                                console.log(error);
                            });
                    } else {
                        console.log('数据未通过校验！');
                        return false;
                    }
                })
            },
            resetForm(formName) {
                if(addDialogVm.$refs[formName])
                    addDialogVm.$refs[formName].resetFields();
            }
        }
    });
    var v_dicid = '[[${dicid}]]';
    var v_groupCode = '[[${groupCode}]]';
    // 查询 模块
    var queryFormVM = new Vue({
        el: '#queryForm',
        data: {
            formInline: {
                "name": '',
                "dicId": v_dicid,
                "groupCode": v_groupCode
            }
        },
        methods: {

            openAddDialog:function(){
                addDialogVm.dialogFormVisible = true;
                addDialogVm.resetForm('add');
            },
            openUpdateDialog:function(){
                if(paginationVm.multipleSelection.length!=1){
                    // queryFormVM.$message.error('请选择一条数据进行编辑');
                    queryFormVM.$message({message: '请选择一条数据进行编辑',type: 'warning'});
                    return false;
                }
                updateDialogVm.resetForm('add');
                updateDialogVm.updateDialogFormVisible = true;
                var row = paginationVm.multipleSelection[0];
                updateDialogVm.initUpdateData(row.id);
            },

            deleteDic:function(){
                var rows = paginationVm.multipleSelection;
                console.log(rows)
                if(rows.length==0){
                    this.$message({
                        message: '请选择删除数据',
                        type: 'warning'
                    });
                    return;
                }else{

                    var names = "";
                    for(var i=0;i<rows.length;i++){
                        names = names + '['+rows[i].name+']';
                    }
                    var str = '确定要删除'+names+'词条?';
                    this.$confirm(str, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var rowIds = [];
                        for(var i=0;i<rows.length;i++){
                            rowIds.push(rows[i].id)
                        }
                        var param={};
                        param.ids = rowIds.join(",");
                        axios.post('/dictionary/DictionaryItem/deleteItemDictionarys', param)
                        .then(function (response) {
                            queryFormVM.$message({type: 'success', message: '确定删除!',duration:2000,onClose:function(){
                                paginationVm.initTableData(1);
                            }});
                        })
                        .catch(function (error) {
                            queryFormVM.$message.error(error);
                            console.log(error);
                        });
                    }).catch(() => {
                        this.$message({type: 'info', message: '已取消删除'});
                    });
                }
            },
            onSubmit() {
                console.log('submit!');
                var param = queryFormVM.formInline;
                param.pageSize = paginationVm.pageSize;
                param.pageNum = paginationVm.pageNum;
                param.dicId = paginationVm.dicid

                console.info(param);
                axios.post('/dictionary/DictionaryItem/queryDictionaryItems', param)
                    .then(function (response) {
                        var data = response.data.data;
                        paginationVm.tableData3 = data.data;
                        paginationVm.total = data.total;
                        paginationVm.currentPage = data.currentPage;
                        paginationVm.pageNum = 1
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        },
        mounted(){ 
          document.getElementById('queryForm').style.display = 'block';
        }
    });
    //var resList=[[${resList}]];
    //带分页的table
    var paginationVm = new Vue({
        el: '#pagination',
        data: {
            tableData3: [],
            multipleSelection:[],
            dicid:v_dicid,
            groupCode:v_groupCode,
            currentPage: 1,
            total: 0,
            pageNum: 1,
            pageSize: 20
        },
        methods: {
            selectRow(row){
            },
            handleSelectionChange(val) {
                console.info(val);
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                //下拉框  每页 10,20条切换 调用
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                localStorage.setItem('allChangePageSize', val);
                this.initTableData(1);
            },
            handleCurrentChange(val) {
                //点击 页码
                console.log(`当前页: ${val}`);
                this.initTableData(val);
            },
            initTableData(v_pageNum) {
                var param = queryFormVM.formInline;
                param.pageSize = this.pageSize;
                param.pageNum = v_pageNum;
                param.dicId = v_dicid;
                axios.post('/dictionary/DictionaryItem/queryDictionaryItems', param)
                    .then(function (response) {
                        var data = response.data.data;
                        console.log(data)
                        if(data){
                            paginationVm.tableData3 = data.data;
                            paginationVm.total = data.total;
                            paginationVm.currentPage = data.currentPage;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
                    .then(function () {
                        // always executed
                    });
            }
        },

        created() {
            console.info("create method");
            var localVal=localStorage.getItem('allChangePageSize')?parseInt(localStorage.getItem('allChangePageSize')):'';
            if(localVal){this.pageSize = localVal;}
            this.initTableData(1);
        },
        mounted() {
            console.info("mounted method");
        }

    });

</script>
</body>
</html>